package banner

import (
	"context"
	"net/http"

	"github.com/gin-gonic/gin"
	"google.golang.org/protobuf/types/known/emptypb"

	"mxshop-api/goods-web/api"
	"mxshop-api/goods-web/forms/banner"
	"mxshop-api/goods-web/global"
	proto "mxshop-api/goods-web/proto/gen/v1"
)

func List(c *gin.Context) {
	resp, err := proto.NewGoodsClient(global.Conn).BannerList(context.Background(), &emptypb.Empty{})
	if err != nil {
		api.HandleGrpcErrorToHttp(c, err)
		return
	}

	data := make([]interface{}, 0, len(resp.Data))
	for _, value := range resp.Data {
		data = append(data, InfoGrpcToMap(value))
	}

	c.JSON(http.StatusOK, gin.H{
		"total": resp.Total,
		"data":  data,
	})
}

func New(c *gin.Context) {
	var bannerIns banner.Form
	err := c.ShouldBind(&bannerIns)
	if err != nil {
		api.HandleValidatorError(c, err)
		return
	}

	resp, err := proto.NewGoodsClient(global.Conn).CreateBanner(context.Background(), &proto.BannerRequest{
		Index: bannerIns.Index,
		Image: bannerIns.Image,
		Url:   bannerIns.Url,
	})
	if err != nil {
		api.HandleGrpcErrorToHttp(c, err)
		return
	}

	c.JSON(http.StatusCreated, gin.H{
		"id":    resp.Id,
		"index": bannerIns.Index,
		"image": bannerIns.Image,
		"url":   bannerIns.Url,
	})
}

func Update(c *gin.Context) {
	var bannerIns banner.Banner
	var form banner.Form
	err := c.ShouldBindUri(&bannerIns)
	if err != nil {
		api.HandleValidatorError(c, err)
		return
	}
	err = c.ShouldBind(&form)
	if err != nil {
		api.HandleValidatorError(c, err)
		return
	}

	_, err = proto.NewGoodsClient(global.Conn).UpdateBanner(context.Background(), &proto.BannerRequest{
		Id:    bannerIns.ID,
		Index: form.Index,
		Image: form.Image,
		Url:   form.Url,
	})
	if err != nil {
		api.HandleGrpcErrorToHttp(c, err)
		return
	}
	c.Status(http.StatusCreated)
}

func Delete(c *gin.Context) {
	var bannerIns banner.Banner
	err := c.ShouldBindUri(&bannerIns)
	if err != nil {
		api.HandleValidatorError(c, err)
		return
	}

	_, err = proto.NewGoodsClient(global.Conn).DeleteBanner(context.Background(), &proto.BannerRequest{
		Id: bannerIns.ID,
	})
	if err != nil {
		api.HandleGrpcErrorToHttp(c, err)
		return
	}
	c.Status(http.StatusNoContent)
}

func InfoGrpcToMap(info *proto.BannerResponse) gin.H {
	return gin.H{
		"id":    info.Id,
		"index": info.Index,
		"image": info.Image,
		"url":   info.Url,
	}
}
